
import Cookie from 'js-cookie'

export default {
    state: {
        menu: [],
        currentMenu: null,
        isCollapsed: false,
        tabsList: [
            {
                path: '/',
                name: 'home',
                label: '首页',
                icon: 'home'
            }
        ],

    },
    mutations: {
        // selectMenu(state, val) {
        //     state.currentMenu = val
        // },

        // 点击菜单处理
        selectMenu(state, val) {
            if (val.name !== 'home') {
                state.currentMenu = val

                // 防止重复加入
                let result = state.tabsList.findIndex(item => item.name === val.name)
                result === -1 ? state.tabsList.push(val) : ''

            } else {
                state.currentMenu = null
            }
            // state.currentMenu = val.name !== 'home' ? val : null
        },

        // 点击展开左侧菜单按钮
        collapseMenu(state) {
            state.isCollapsed = !state.isCollapsed
        },

        // 关闭标签处理
        closeTab(state, val) {
            let result = state.tabsList.findIndex(item => item.name === val.name)

            // 从tab数组中删除
            state.tabsList.splice(result, 1)
        },

        // 设置菜单
        setMenu(state, val) {
            state.menu = val
            Cookie.set('menu', JSON.stringify(val))
            console.log(val, 'vuex')
        },

        // 登出菜单
        clearMenu(state) {
            // 清空菜单
            state.menu = []
            Cookie.remove('menu')
        },

        // 添加菜单
        addMenu(state, router) {
            if (!Cookie.get('menu')) {
                return
            }
            let menu = JSON.parse(Cookie.get('menu'))
            state.menu = menu

            // 设置当前菜单
            let currentMenu = [
                {
                    path: '/',
                    component: () => import(`@/views/Main`),
                    children: []
                }
            ]
            menu.forEach(item => {
                if (item.children) {
                    item.children = item.children.map(item => {
                        item.component = () => import(`@/views/${item.url}`)
                        return item
                    })
                    // 添加动态路由
                    currentMenu[0].children.push(...item.children)
                } else {
                    item.component = () => import(`@/views/${item.url}`)
                    currentMenu[0].children.push(item)
                }
            })
            console.log(currentMenu, 'cur')
            router.addRoutes(currentMenu)
        }
    },
    actions: {}
}